package cn.itrigger.dynamic.sql.select.render;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * @author admin
 * @date 2018/9/25
 **/
public class QueryExpressionCollector {
    private List<String> queryExpressions = new ArrayList<>();
    private Map<String, Object> parameters = new HashMap<>();

    private QueryExpressionCollector() {
        super();
    }

    private void add(QueryExpression queryExpression) {
        queryExpressions.add(queryExpression.queryExpression());
        parameters.putAll(queryExpression.getParameters());
    }

    private QueryExpressionCollector merge(QueryExpressionCollector other) {
        queryExpressions.addAll(other.queryExpressions);
        parameters.putAll(other.parameters);
        return this;
    }

    public String queryExpression() {
        return queryExpressions.stream().collect(Collectors.joining(" "));
    }

    public Map<String, Object> getParameters() {
        return parameters;
    }

    public static Collector<QueryExpression, QueryExpressionCollector, QueryExpressionCollector> collect() {
        return Collector.of(QueryExpressionCollector::new,
                QueryExpressionCollector::add,
                QueryExpressionCollector::merge);
    }
}
